#include "protocol.h"

uint32_t send_sn = 0;


static uint32_t get_pack_check(uint8_t *buf,uint32_t length)
{
	int i = 0;
	uint32_t sum = 0;
	for(i = 0; i < length;i++)
	{
		sum += buf[i];
	}
	return sum;
}


uint32_t protocol_sample_info_pack(uint8_t *buf,uint32_t buf_size,void *info)
{
	if(buf == NULL || buf_size < sizeof(protocol_sample_info_t) || info == NULL)
	{
		return 0;
	}
	protocol_sample_info_t pack;
	protocol_sample_info_pack_t *ptr = (protocol_sample_info_pack_t*)info;


	pack.header.magic_num = 0xA55A;
	pack.header.pack_type = PACK_TYPE_DS_EXPERIMENT_DATA;
	pack.header.pack_len = sizeof(protocol_sample_info_t);
	pack.header.pack_sn = send_sn++;
	//header
	memcpy((uint8_t*)&pack.pack,(uint8_t*)ptr,sizeof(protocol_sample_info_pack_t));
	pack.crc32 = get_pack_check((uint8_t*)&pack,sizeof(protocol_sample_info_t) - sizeof(uint32_t));
	memcpy(buf,(uint8_t*)&pack,sizeof(protocol_sample_info_t));
	return sizeof(protocol_sample_info_t);
}


uint32_t protocol_print_pack(uint8_t *buf,uint32_t buf_size,const char *fmt,uint32_t fmt_length)
{
	if(buf == NULL || buf_size < sizeof(protocol_header_t)+4 || fmt == NULL || fmt_length == 0)
	{
		return 0;
	}
	uint32_t ret = 0;
	uint32_t offset = 0;
	
	protocol_header_t header;
	header.magic_num = 0xA55A;
	header.pack_type = PACK_TYPE_PRINT_LOG;
	header.pack_len = sizeof(protocol_header_t) + fmt_length + sizeof(uint32_t);
	header.pack_sn = send_sn++;		
	memcpy(buf+offset,(uint8_t*)&header,sizeof(protocol_header_t));
	/*copy the header data*/
	offset += sizeof(protocol_header_t);
	
	memcpy(buf+offset,fmt,fmt_length);
	offset += fmt_length;
	union
	{
		uint32_t u32_;
		uint8_t u8_[4];
	}u32tou8;
	u32tou8.u32_ = get_pack_check(buf,offset);
	memcpy(buf+offset,u32tou8.u8_,4);
	offset += 4;
	ret = offset;
	return ret;
}



void hc_printf(const char *fmt,...)
{
	char fmt_buf[ MAX_QUEUE_PACK_SIZE - sizeof(protocol_header_t) - sizeof(uint32_t) ] = "\0"; 
	uint8_t pack[MAX_QUEUE_PACK_SIZE] = {0};
	uint32_t pack_len;
	int fmt_len;
	memset(fmt_buf,0,sizeof(fmt_buf));
	va_list args;
	va_start(args, fmt);
	fmt_len = vsnprintf(fmt_buf, sizeof(fmt_buf), fmt, args);
	va_end(args);	

	pack_len = protocol_print_pack(pack, sizeof(pack),fmt_buf,fmt_len);
	
	//Bsp_USB_SendData(pack,pack_len);
	Bsp_Usart_SendData(pack,pack_len);
	
}


